Root Zanli
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
home
/
o5t6x7pgljbm
/
public_html
/
admin
/
app
/
V2
/
Services
/
Filename :
ImageDownloaderService.php
back
Copy
<?php namespace App\V2\Services; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; class ImageDownloaderService { /** * Download an image from a URL and store it locally. * * @param string $url * @return string|bool The local file path of the downloaded image, or false on failure. */ public function downloadImage($url, $target_folder, $default_file_url) { Log::debug("File to download: ". print_r( ['url' => $url, 'target_folder' => $target_folder, 'default_file_url' => $default_file_url] , true)); try { // Send a HEAD request to get the content type $response = Http::head($url); // Check if the content type is an image $contentType = $response->header('Content-Type'); if (Str::startsWith($contentType, 'image/')) { // Send a GET request to download the image $response = Http::get($url); // Check if the request was successful if ($response->successful()) { // Generate a unique file name $extension = explode('/', $contentType)[1]; // $fileName = Str::random(40) . '.' . $extension; $fileName = rand().time().'.'.$extension; // Define the path to store the file $filePath = public_path($target_folder); // Store the file locally in the public/app-assets directory file_put_contents($filePath."/".$fileName, $response->body()); // Return the local file path return $fileName; } } else { return $default_file_url; } } catch (\Exception $e) { // Log the error or handle it as needed Log::error('Failed to download image: ' . $e->getMessage()); } return $default_file_url; } }